package com.fsy.its.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsy.common.mqtt.MqttGateway;
import com.fsy.common.redis.RedisUtil;
import com.fsy.its.dao.DtuMapper;
import com.fsy.its.entity.Dtu;
import com.fsy.its.util.Const;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.fsy.its.util.Const.CACHE_KEY_DTUS;
import static com.fsy.its.util.Const.CACHE_KEY_DTU_PRE;

@Service
public class DtuService extends ServiceImpl<DtuMapper, Dtu>  {

    @Autowired
    private RedisUtil redis;

    @Autowired
    private MqttGateway mqttGateway;

    @Cacheable(value="its.db.dtu", key="#dtuId")
    public Dtu getDtu(String dtuId) {
        return baseMapper.getDtuById(dtuId);
    }

    public void clearDtuCache() {
        Set<Object> dtus = redis.sget(CACHE_KEY_DTUS);
        for( Object dtuId : dtus ) {
            redis.hdel(CACHE_KEY_DTU_PRE + dtuId);
        }
        redis.sRemove(CACHE_KEY_DTUS);
    }

    public void dtuOnline(Dtu dtu) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        redis.sadd(CACHE_KEY_DTUS, dtu.getId());
        Map<String, String> map = BeanUtils.describe(dtu);
        redis.hmset(CACHE_KEY_DTU_PRE+dtu.getId(), new HashMap<>(map));

        String topic = Const.TOPIC_DTU_ONLINE + dtu.getId();
        String data = JSON.toJSONString(dtu);
        mqttGateway.sendToMqtt(data, topic);
    }

    public void dtuOffline(Dtu dtu) {
        redis.sRemove(CACHE_KEY_DTUS, dtu.getId());
        redis.hdel(CACHE_KEY_DTU_PRE + dtu.getId());

        String topic = Const.TOPIC_DTU_OFFLINE + dtu.getId();
        String data = JSON.toJSONString(dtu);
        mqttGateway.sendToMqtt(data, topic);
    }
}
